package server

import (
	"context"
	"github.com/go-co-op/gocron"
	"github.com/go-kratos/kratos/v2/log"
	"phm/internal/conf"
	"phm/internal/service/gojob"
	myStrings "phm/tools/strings"
	"time"
)

type CronServer struct {
	c         *conf.Job
	scheduler *gocron.Scheduler
	logger    *log.Helper
}

func NewCronServer(jobService *gojob.JobService, logger log.Logger) (s *CronServer) {
	jobService.Init()
	// 当前工作的job：
	var workingJobName = myStrings.NewStrBuilder()
	s = &CronServer{
		c:         conf.Config.Job,
		scheduler: gocron.NewScheduler(time.Local),
		logger:    log.NewHelper(logger),
	}
	for _, j := range s.c.Jobs {
		if j.Switch {
			job, ok := gojob.DefaultJobs[j.Name]
			workingJobName.StrAppend("[ ").StrAppend(j.Name).StrAppend(" ] ")
			if !ok {
				log.Warnf("[corn] server job不存在: %s", j.Name)
				continue
			}
			_, err := s.scheduler.Cron(j.Schedule).Do(func(name string) {
				log.Info("[corn] server job运行: ", name)
				job()
			}, j.Name)
			if err != nil {
				panic(err)
			}
		}
	}
	s.logger.Info("[corn] server 加载job数量: ", len(s.scheduler.Jobs()), "=> ", workingJobName.ToString())
	return s
}

func (s *CronServer) Start(c context.Context) error {
	s.scheduler.StartAsync()
	return nil
}

func (s *CronServer) Stop(c context.Context) error {
	s.scheduler.Stop()
	return nil
}
